/**
 * 外部音频服务 - 处理来自外部平台的音乐URL
 */
class ExternalAudioService {
  constructor() {
    this.audioProxies = new Map()
    this.retryAttempts = new Map()
    this.maxRetries = 3
  }

  /**
   * 检测是否为外部音乐URL
   */
  isExternalUrl(url) {
    if (!url) return false
    
    const externalDomains = [
      'music.163.com',
      'y.qq.com',
      'stream.qqmusic.qq.com',
      'kugou.com',
      'kuwo.cn',
      'soundcloud.com',
      'spotify.com'
    ]
    
    return externalDomains.some(domain => url.includes(domain))
  }

  /**
   * 获取音乐平台类型
   */
  getMusicPlatform(url) {
    if (url.includes('music.163.com')) return 'netease'
    if (url.includes('y.qq.com') || url.includes('stream.qqmusic.qq.com')) return 'qq'
    if (url.includes('kugou.com')) return 'kugou'
    if (url.includes('kuwo.cn')) return 'kuwo'
    if (url.includes('soundcloud.com')) return 'soundcloud'
    if (url.includes('spotify.com')) return 'spotify'
    return 'unknown'
  }

  /**
   * 处理外部音乐URL
   */
  async processExternalUrl(originalUrl) {
    try {
      const platform = this.getMusicPlatform(originalUrl)
      console.log(`🎵 处理${platform}平台音乐URL:`, originalUrl)

      switch (platform) {
        case 'netease':
          return await this.processNeteaseUrl(originalUrl)
        case 'qq':
          return await this.processQQUrl(originalUrl)
        default:
          return await this.processGenericUrl(originalUrl)
      }
    } catch (error) {
      console.error('处理外部音乐URL失败:', error)
      throw error
    }
  }

  /**
   * 处理网易云音乐URL
   */
  async processNeteaseUrl(url) {
    try {
      console.log('🎵 处理网易云音乐URL:', url)
      
      // 网易云音乐有CORS限制，必须通过后端代理
      console.log('🌐 网易云音乐需要通过代理访问')
      
      // 使用后端代理流接口
      const proxyStreamUrl = `http://localhost:2025/api/audio/stream?url=${encodeURIComponent(url)}`
      console.log('🔄 生成代理流URL:', proxyStreamUrl)
      return proxyStreamUrl
      
    } catch (error) {
      console.error('处理网易云音乐URL失败:', error)
      // 降级策略：返回代理流URL
      const proxyStreamUrl = `http://localhost:2025/api/audio/stream?url=${encodeURIComponent(url)}`
      return proxyStreamUrl
    }
  }

  /**
   * 处理QQ音乐URL
   */
  async processQQUrl(url) {
    try {
      console.log('🎵 处理QQ音乐URL:', url)
      
      // QQ音乐也有CORS限制，使用代理
      console.log('🌐 QQ音乐需要通过代理访问')
      const proxyStreamUrl = `http://localhost:2025/api/audio/stream?url=${encodeURIComponent(url)}`
      console.log('🔄 生成代理流URL:', proxyStreamUrl)
      return proxyStreamUrl
      
    } catch (error) {
      console.error('处理QQ音乐URL失败:', error)
      // 降级策略：返回代理流URL
      const proxyStreamUrl = `http://localhost:2025/api/audio/stream?url=${encodeURIComponent(url)}`
      return proxyStreamUrl
    }
  }

  /**
   * 处理通用外部URL
   */
  async processGenericUrl(url) {
    try {
      console.log('🎵 处理通用外部URL:', url)
      
      // 对于外部URL，统一使用代理来避免CORS问题
      console.log('🌐 外部URL使用代理访问以避免CORS问题')
      const proxyStreamUrl = `http://localhost:2025/api/audio/stream?url=${encodeURIComponent(url)}`
      console.log('🔄 生成代理流URL:', proxyStreamUrl)
      return proxyStreamUrl
      
    } catch (error) {
      console.error('处理通用外部URL失败:', error)
      // 降级策略：返回代理流URL
      const proxyStreamUrl = `http://localhost:2025/api/audio/stream?url=${encodeURIComponent(url)}`
      return proxyStreamUrl
    }
  }

  /**
   * 通过后端代理获取音频URL
   */
  async getProxyUrl(originalUrl, platform) {
    try {
      const response = await fetch('http://localhost:2025/api/audio/proxy', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
        body: JSON.stringify({
          url: originalUrl,
          platform: platform
        })
      })

      if (response.ok) {
        const data = await response.json()
        console.log('✅ 代理URL获取成功:', data.proxyUrl)
        return data.proxyUrl
      } else {
        console.warn('❌ 代理服务响应错误:', response.status, response.statusText)
      }
    } catch (error) {
      console.warn('❌ 获取代理URL失败，将直接使用原始URL:', error.message)
    }
    
    return null
  }

  /**
   * 检查URL可访问性
   */
  async checkUrlAccessibility(url) {
    try {
      // 创建一个临时的audio元素来测试URL
      const audio = new Audio()
      audio.crossOrigin = 'anonymous'
      
      return new Promise((resolve) => {
        const timeout = setTimeout(() => {
          resolve(false)
        }, 5000) // 5秒超时

        audio.addEventListener('canplay', () => {
          clearTimeout(timeout)
          resolve(true)
        }, { once: true })

        audio.addEventListener('error', () => {
          clearTimeout(timeout)
          resolve(false)
        }, { once: true })

        audio.src = url
        audio.load()
      })
    } catch (error) {
      return false
    }
  }

  /**
   * 创建兼容的音频元素
   */
  createCompatibleAudio(url) {
    const audio = new Audio()
    
    // 根据URL类型设置不同的属性
    if (this.isExternalUrl(url)) {
      // 外部URL的设置
      audio.crossOrigin = 'anonymous'
      audio.preload = 'metadata' // 改为metadata以支持后台播放
      
      // 添加特殊的error处理
      audio.addEventListener('error', async (event) => {
        await this.handleExternalAudioError(event, url, audio)
      })
    } else {
      // 本地文件的设置
      audio.crossOrigin = 'use-credentials'
      audio.preload = 'metadata'
    }

    return audio
  }

  /**
   * 处理外部音频错误
   */
  async handleExternalAudioError(event, originalUrl, audioElement) {
    const retryKey = originalUrl
    const currentRetries = this.retryAttempts.get(retryKey) || 0

    if (currentRetries < this.maxRetries) {
      console.log(`🔄 外部音频加载失败，尝试重试 (${currentRetries + 1}/${this.maxRetries}):`, originalUrl)
      
      this.retryAttempts.set(retryKey, currentRetries + 1)
      
      try {
        // 尝试重新处理URL
        const newUrl = await this.processExternalUrl(originalUrl)
        if (newUrl !== originalUrl) {
          console.log('🎵 使用新的音频URL:', newUrl)
          audioElement.src = newUrl
          audioElement.load()
          return
        }
      } catch (error) {
        console.error('重新处理URL失败:', error)
      }
    }

    console.error('❌ 外部音频最终加载失败:', originalUrl)
    this.retryAttempts.delete(retryKey)
  }

  /**
   * 设置音频元素的源
   */
  async setAudioSource(audioElement, url) {
    try {
      console.log('🔧 开始设置音频源:', url)
      
      if (this.isExternalUrl(url)) {
        // 处理外部URL
        console.log('🌐 识别为外部URL，开始处理...')
        const processedUrl = await this.processExternalUrl(url)
        
        // 代理URL应该作为本地URL处理（因为代理服务器在本地）
        if (processedUrl.includes('localhost:2025')) {
          console.log('🔄 代理URL，设置为本地访问模式')
          audioElement.crossOrigin = 'use-credentials'
          audioElement.preload = 'auto'
        } else {
          // 仍然是外部URL
          audioElement.crossOrigin = 'anonymous'
          audioElement.preload = 'metadata' // 改为metadata以支持后台播放
        }
        
        console.log('🎵 设置外部音频源:', processedUrl)
        audioElement.src = processedUrl
      } else {
        // 处理本地URL
        console.log('📁 识别为本地URL')
        audioElement.crossOrigin = 'use-credentials'
        audioElement.preload = 'auto'
        
        audioElement.src = url
        console.log('🎵 设置本地音频源:', url)
      }
      
      // 添加错误监听器
      audioElement.addEventListener('error', (event) => {
        console.error('❌ 音频加载错误:', {
          error: event.target.error,
          src: event.target.src,
          code: event.target.error?.code,
          message: event.target.error?.message
        })
      }, { once: true })
      
      // 添加加载成功监听器
      audioElement.addEventListener('canplay', () => {
        console.log('✅ 音频可以播放:', audioElement.src)
      }, { once: true })
      
      audioElement.load()
      console.log('📡 音频元素开始加载...')
      
    } catch (error) {
      console.error('❌ 设置音频源失败:', error)
      // 降级策略：直接设置原始URL
      try {
        console.log('🔄 使用降级策略，直接设置原始URL')
        audioElement.crossOrigin = 'use-credentials'
        audioElement.src = url
        audioElement.load()
      } catch (fallbackError) {
        console.error('❌ 降级策略也失败:', fallbackError)
      }
    }
  }

  /**
   * 清理资源
   */
  cleanup() {
    this.audioProxies.clear()
    this.retryAttempts.clear()
  }
}

// 创建全局实例
const externalAudioService = new ExternalAudioService()

export default externalAudioService 